import React from 'react';
import { Card, Avatar, Rate, Tooltip, List, Tag, message } from 'antd';
import {
  EditOutlined,
  HeartOutlined,
  HeartTwoTone,
  LoginOutlined,
  ShareAltOutlined,
  EllipsisOutlined,
  SettingOutlined,
} from '@ant-design/icons';
import styles from './index.less';
import defaultPic from '@/assets/defaultIcon.png';
import { useState } from 'react';
import { useEffect } from 'react';
import TagList from '@/components/TagList';
import { history } from 'umi';
import Paragraph from 'antd/lib/skeleton/Paragraph';
import copy from 'copy-to-clipboard';
import { getLink, like } from '@/services/ant-design-pro/links';
import { addBookmark, delBookmark } from '@/services/ant-design-pro/user';

const { Meta } = Card;

const ResourceCard = (props) => {
  const { resourceId, recommend } = props;
  const [resource, setResource] = useState(props);
  // 星级
  const [start, setStart] = useState('');
  // 收藏数
  const [bookmarkCnt, setBookmarkCnt] = useState(0);
  // 是否收藏
  const [isMarked, setIsMarked] = useState(false);
  const [statue, setStatue] = useState(2);
  const [tips, setTips] = useState(resource.tips);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (loading === false) {
      requestLink({ id: resourceId });
      setLoading(true);
    }
  });

  // 请求资源
  const requestLink = async (values) => {
    try {
      const res = await getLink({ ...values });
      console.log(res);
      setResource(res.data);
      setStart(res.data.start);
      setBookmarkCnt(res.data.bookmarkCnt);
      setIsMarked(res.data.isBookmarked);
      setStatue(res.data.status);
      // console.log(res.data.id);
      // if (res.data !== resource) {
      //   setResource(res.data);
      // }
    } catch (error) {
      console.log(error);
    }
  };

  // 是否收藏，后期改成接口
  const isLike = false;
  // 后期改成接口
  const showActions = true;

  // 跳转详情
  const toDetail = () => {
    // if (!showActions) {
    //   return;
    // }
    // if (prePageState) {
    //   localStorage.setItem(PRE_PAGE_STATE, JSON.stringify(prePageState));
    // }
    history.push({
      pathname: '/rd/',
      query: {
        rid: resource.id,
      },
    });
  };

  // 收藏
  const mark = async (values) => {
    if (isMarked === false) {
      try {
        const res = await addBookmark({ ...values });
        setBookmarkCnt(bookmarkCnt + 1);
        setIsMarked(true);
        message.success('收藏成功');
      } catch (error) {
        console.log(error);
      }
    } else {
      try {
        const res = await delBookmark({ ...values });
        setBookmarkCnt(bookmarkCnt - 1);
        setIsMarked(false);
        message.success('取消收藏成功');
      } catch (error) {
        console.log(error);
      }
    }
  };

  // 分享链接
  const doShare = () => {
    copy(`${resource.url}`);
    message.success('链接已复制，快去分享吧！');
  };

  // 访问资源
  const doSearch = () => {
    if (resource.url) {
      window.open(resource.url);
    } else {
      window.open(`http://www.baidu.com/s?wd=${resource.name}`);
    }
  };

  // 审核状态
  const statueTags = [];
  if (statue === 1) {
    statueTags.push(
      <Tag key="new" color="blue">
        审核中
      </Tag>,
    );
  } else if (statue === 2) {
    statueTags.push(
      <Tag key="new" color="green">
        审核通过
      </Tag>,
    );
  } else {
    statueTags.push(
      <Tag key="new" color="red">
        审核未通过
      </Tag>,
    );
  }

  const actions = showActions
    ? [
        <Tooltip title={isMarked ? '取消收藏' : '收藏'}>
          <div onClick={() => mark({ id: resource.id })}>
            {isMarked ? (
              <>
                <HeartTwoTone twoToneColor="red" />
                <span style={{ color: 'red' }}> {bookmarkCnt}</span>
              </>
            ) : (
              <>
                <HeartOutlined /> {bookmarkCnt}
              </>
            )}
          </div>
        </Tooltip>,
        <Tooltip title="分享">
          <div onClick={doShare}>
            <ShareAltOutlined />
          </div>
        </Tooltip>,
        <Tooltip title="访问">{<LoginOutlined onClick={doSearch} />}</Tooltip>,
      ]
    : [];

  // // 审核拒绝状态才允许修改
  // if (showEdit && resource.reviewStatus === reviewStatusEnum.REJECT) {
  //   actions.push(
  //     <div onClick={doEdit}>
  //       <EditOutlined />
  //     </div>,
  //   );
  // }

  return (
    <Card className={styles.card} hoverable={true} actions={actions}>
      <div onClick={toDetail}>
        <Meta
          avatar={
            <>
              <Avatar
                src={resource.icon ? 'http://localhost:9999' + resource.icon : defaultPic}
                alt={resource.name}
              />
              {start && (
                <Rate
                  disabled
                  allowHalf
                  count={start}
                  defaultValue={start}
                  className={styles.starRate}
                />
              )}
            </>
          }
          className={styles.cardMeta}
          title={resource.name}
          // title={
          //   <Tooltip
          //     title={
          //       <Paragraph style={{ color: '#fff', marginBottom: 0 }}>
          //         <span dangerouslySetInnerHTML={{ __html: resource.name ?? '' }} />
          //       </Paragraph>
          //     }
          //   >
          //     <div dangerouslySetInnerHTML={{ __html: resource.name ?? '' }} />
          //   </Tooltip>
          // }
          description={
            resource.desc
            // <Paragraph ellipsis={{ rows: 3 }} type="secondary" style={{ marginBottom: 0 }}>
            //   <span dangerouslySetInnerHTML={{ __html: resource.desc ?? '' }} />
            // </Paragraph>
          }
        />
        {recommend ? statueTags : ''}
        <TagList tips={resource.tips} style={{ minHeight: 60 }}></TagList>
      </div>
    </Card>
  );
};

export default ResourceCard;
